package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.exception.BaseException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        if (begin.isAfter(end)) {
            throw new BaseException("日期参数错误，请校验");
        }
        //首先计算datalist，直接计算,新建list用于存储日期
        List<LocalDate> dateList = new ArrayList<>();
        //存放每天的营业额
        List<BigDecimal> valueList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //StringUtils 是lang3的包

        for (LocalDate date : dateList) {
            //这里的营业额指的是，状态为“已完成”的订单的金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//获取当天时间的最小值
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//获取当前时间最大值

            Map<String,Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            BigDecimal turnover = orderMapper.sumByMapp(map);//如果当天的营业额为空的话，读取到的数值并不是0而是null
            turnover = turnover==null?BigDecimal.ZERO:turnover;//此处对null的情况进行判断
            valueList.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(valueList, ","))
                .build();
    }

    @Override
    public UserReportVO getuserStatistics(LocalDate begin, LocalDate end) {
        if (begin.isAfter(end)) {
            throw new BaseException("日期参数错误，请校验");
        }
        //首先计算datalist，直接计算,新建list用于存储日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<BigInteger> valueList = new ArrayList<>();
        List<BigInteger> newValueList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String,Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            valueList.add(userMapper.countAll());
            newValueList.add(userMapper.countAllByTime(map));
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newValueList, ","))
                .totalUserList(StringUtils.join(valueList, ","))
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        if (begin.isAfter(end)) {
            throw new BaseException("日期参数错误，请校验");
        }
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");

        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        //封装返回结果数据
        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //状态为已完成的订单为有效订单
        //订单完成率=有效订单数/总订单数*100%
        if (begin.isAfter(end)) {
            throw new BaseException();
        }
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //每日订单数,有效订单数
        List<Integer> orderNumberList = new ArrayList<>();
        List<Integer> orderGoodNumberList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String,Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            orderNumberList.add(orderMapper.getNum(map));
            orderGoodNumberList.add(orderMapper.getGoodNum(map));
        }
        Double totalOrderNumber = orderNumberList.stream().reduce(0, Integer::sum).doubleValue();
        Double validOrderNumber = orderGoodNumberList.stream().reduce(0, Integer::sum).doubleValue();


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderNumberList, ","))
                .validOrderCountList(StringUtils.join(orderGoodNumberList, ","))
                .totalOrderCount(totalOrderNumber.intValue())
                .validOrderCount(validOrderNumber.intValue())
                .orderCompletionRate( validOrderNumber/ totalOrderNumber)
                .build();
    }

    @Override
    public void exportBussinessData(HttpServletResponse response) throws IOException {
        /*
        1.查询数据库，获取营业数据
        2.通过POI将数据写入到Excel文件中
        3.通过输出流将Excel文件下载到客户端浏览器
        */
        // 计算时间范围
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dateEnd, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        // 加载 Excel 模板
        XSSFWorkbook excel = null;
        try (InputStream input = this.getClass().getClassLoader().getResourceAsStream("template/template.xlsx")) {
            if (input != null) {
                excel = new XSSFWorkbook(input);
            } else {
                throw new IOException("无法找到模板文件");
            }
        }

        // 填充数据
        String dateMessage = "时间：" + dateBegin.toString() + " - " + dateEnd.toString();
        XSSFSheet sheet = excel.getSheet("Sheet1");

        // 填充第一行日期信息
        XSSFRow row = sheet.getRow(1);
        if (row == null) {
            row = sheet.createRow(1);
        }
        if (row.getCell(0) == null) {
            row.createCell(0);
        }
        row.getCell(0).setCellValue(dateMessage);

        // 填充第四行数据
        XSSFRow row4 = sheet.getRow(4);
        if (row4 == null) {
            row4 = sheet.createRow(4);
        }
        if (row4.getCell(1) == null) {
            row4.createCell(1);
        }
        row4.getCell(1).setCellValue(businessData.getTurnover());
        if (row4.getCell(3) == null) {
            row4.createCell(3);
        }
        row4.getCell(3).setCellValue(businessData.getOrderCompletionRate());
        if (row4.getCell(5) == null) {
            row4.createCell(5);
        }
        row4.getCell(5).setCellValue(businessData.getNewUsers());

        // 填充第五行数据
        XSSFRow row5 = sheet.getRow(5);
        if (row5 == null) {
            row5 = sheet.createRow(5);
        }
        if (row5.getCell(1) == null) {
            row5.createCell(1);
        }
        row5.getCell(1).setCellValue(businessData.getValidOrderCount());
        if (row5.getCell(3) == null) {
            row5.createCell(3);
        }
        row5.getCell(3).setCellValue(businessData.getUnitPrice());

        // 填充每日数据
        for (int i = 0; i < 30; i++) {
            LocalDate begin = dateBegin.plusDays(i);
            LocalDate end = begin.plusDays(1);
            LocalDateTime timeStart = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime timeEnd = LocalDateTime.of(end, LocalTime.MAX);
            BusinessDataVO businessData1 = workspaceService.getBusinessData(timeStart, timeEnd);
            XSSFRow rows = sheet.getRow(7 + i);
            if (rows == null) {
                rows = sheet.createRow(7 + i);
            }
            if (rows.getCell(0) == null) {
                rows.createCell(0);
            }
            rows.getCell(0).setCellValue(String.valueOf(begin));
            if (rows.getCell(1) == null) {
                rows.createCell(1);
            }
            rows.getCell(1).setCellValue(businessData1.getTurnover());
            if (rows.getCell(3) == null) {
                rows.createCell(3);
            }
            rows.getCell(3).setCellValue(businessData1.getOrderCompletionRate());
            if (rows.getCell(5) == null) {
                rows.createCell(5);
            }
            rows.getCell(5).setCellValue(businessData1.getNewUsers());
            if (rows.getCell(2) == null) {
                rows.createCell(2);
            }
            rows.getCell(2).setCellValue(businessData1.getValidOrderCount());
            if (rows.getCell(4) == null) {
                rows.createCell(4);
            }
            rows.getCell(4).setCellValue(businessData1.getUnitPrice());
        }


        //通过输出流下载
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);

        //关闭资源
        excel.close();
        outputStream.close();

    }
}
